<?php
/**
 * @ClassName: Equipment
 * @Description: TODO
 * @author: ynbjykj
 * @Date: 2025-11-26 10:34
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\enum\RackEnum;
use app\common\logic\EquipmentLogic;
use app\common\model;
use think\Db;

class Equipment extends Api
{
    /**
     * 统计数据
     * @return \think\response\Json
     */
    function index()
    {
        $store_id = input('store_id', 0);
        $flag = input('flag', 'agent');

        $where = [];

        switch ($flag) {
            case 'master':
            case 'merchant':
            case 'store':
            case 'staff':
                //师傅、商家、门店、员工
                $where[] = ['holder_type', '=', model\Equipment::holder_type_store];
                $where[] = ['h_related_id', '=', $store_id];
                break;
            case 'agent':
                //代理
                $where[] = ['holder_type', '=', model\Equipment::holder_type_agent];
                $where[] = ['h_related_id', '=', $this->user_id];
                break;
            default:
                //其他
                break;
        }

        $total = model\Equipment::where($where)->count();
        $installed_num = model\Equipment::where($where)->where('status', 1)->count();
        $notinstalled_num = $total - $installed_num;

        $result = [
            'total' => $total,
            'installed_num' => $installed_num,
            'notinstalled_num' => $notinstalled_num,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    function list()
    {
        $store_id = input('store_id', 0);
        $current = input('current', 0);
        $flag = input('flag', 'agent');
        $device_type = input('device_type', 0);
        $device_model = input('device_model', 0);
        $sales_method = input('sales_method', 0);
        $ad_position = input('ad_position', 0);
        $province = input('province', 0);
        $city = input('city', 0);
        $area = input('area', 0);
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [];

        if ($device_type) {
            $where[] = ['e.device_type', '=', $device_type];
        }

        if ($device_model) {
            $where[] = ['e.grids_num', '=', $device_model];
        }

        if ($sales_method) {
            $where[] = ['e.sales_method', '=', $sales_method];
        }

        switch ($flag) {
            case 'master':
            case 'merchant':
            case 'store':
            case 'staff':
                //师傅、商家、门店、员工
                $where[] = ['e.holder_type', '=', model\Equipment::holder_type_store];
                $where[] = ['e.h_related_id', '=', $store_id];
                break;
            case 'agent':
                //代理
                //代理
                $where[] = ['e.holder_type', '=', model\Equipment::holder_type_agent];
                $where[] = ['e.h_related_id', '=', $this->user_id];
                break;
            default:
                //其他
                break;
        }

        if ($current == 1) {
            $where[] = ['e.status', '=', RackEnum::status_used];

            if ($ad_position) {
                $where[] = ['ec.ad_put_location', 'like', '%,' . $ad_position . ',%'];
            }

            if ($area) {
                $where[] = ['ec.area', '=', $area];
            } else {
                if ($city) {
                    $where[] = ['ec.city', '=', $city];
                } else {
                    if ($province) {
                        $where[] = ['ec.province', '=', $province];
                    }
                }
            }

            $list = model\Equipment::alias('e')->distinct('e.id')
                ->leftJoin('equipment_customer ec', 'ec.device_id=e.id')
                ->where($where)
                ->field('e.*')
                ->limit($skip, $limit)->select();

            foreach ($list as $key => &$item) {
                $info = model\EquipmentCustomer::where('device_id', $item['id'])->where('status', 1)->find();
                if ($info) {
                    $item['info'] = $info;
                    $item['customer'] = model\Customer::get($info['customer_id']);
                } else {
                    unset($list[$key]);
                }
            }
        } elseif ($current == 2) {
            $where[] = ['e.status', '=', RackEnum::status_unused];
            $list = model\Equipment::alias('e')->where($where)->limit($skip, $limit)->select();
        } else {
            $list = [];
        }

        $result = [
            'list' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 绑定客户
     * @return \think\response\Json
     */
    function bindCustomer()
    {
        $device_id = input('device_id', 0);
        $customer_id = input('customer_id', 0);
        $use_grids_num = input('use_grids_num', 0);
        $water_threshold = input('water_threshold', 0);
        $location_desc = input('location_desc', '');

        $device = model\Equipment::get($device_id);
        if (!$device) {
            return json(['code' => 0, 'msg' => '设备信息不存在']);
        }

        $customer = model\Customer::get($customer_id);
        if (!$customer) {
            return json(['code' => 0, 'msg' => '客户信息不存在']);
        }

        $add_data = [
            'device_type' => $device['device_type'],
            'customer_id' => $customer_id,
            'device_id' => $device_id,
            'region_id' => 0,
            'province' => $customer['province'],
            'city' => $customer['city'],
            'area' => $customer['area'],
            'town' => $customer['town'],
            'address' => $customer['address'],
            'location_desc' => $location_desc,
            'longitude' => $customer['longitude'],
            'latitude' => $customer['latitude'],
            'grids_num' => $device['grids_num'],
            'bucketful_num' => 0,
            'empty_bucket_num' => $use_grids_num,
            'flow_card' => $device['flow_card_no'],
            'electricity' => $device['dump_energy'],
            'battery_voltage' => $device['battery_voltage'],
            'status' => 1,
            'water_threshold' => $water_threshold,
            'create_time' => date_now(),
            'update_time' => date_now(),
        ];

        Db::startTrans();
        try {
            $res = model\EquipmentCustomer::insert($add_data);

            //更新设备信息
            $res1 = model\Equipment::where('id', $device_id)->update([
                'use_type' => model\Equipment::use_type_customer,
                'u_related_id' => $customer_id,
                'status' => RackEnum::status_used,
                'update_time' => date_now(),
            ]);

            if ($res && $res1) {
                Db::commit();
                return json(['code' => 1, 'msg' => '绑定成功']);
            }
        } catch (\Exception $e) {
            trace($e);
        }

        Db::rollback();
        return json(['code' => 0, 'msg' => '绑定失败']);
    }

    /**
     * 解绑客户
     * @return \think\response\Json
     */
    function unbindCustomer()
    {
        $device_id = input('device_id', 0);

        Db::startTrans();
        try {
            $res = model\EquipmentCustomer::where('device_id', $device_id)->where('status', 1)->update([
                'status' => 0,
                'update_time' => date_now(),
                'delete_time' => date_now(),
            ]);

            //更新设备信息
            $res1 = model\Equipment::where('id', $device_id)->update([
                'status' => RackEnum::status_unused,
                'update_time' => date_now(),
            ]);

            if ($res && $res1) {
                Db::commit();
                return json(['code' => 1, 'msg' => '解绑成功']);
            }
        } catch (\Exception $e) {
            trace($e);
        }

        Db::rollback();
        return json(['code' => 0, 'msg' => '解绑失败']);
    }

    /**
     * 设备回拨
     * @return \think\response\Json
     */
    function callback()
    {
        $device_id = input('device_id', 0);
        $operator_type = input('operator_type', model\Equipment::holder_type_agent);

        $device = model\Equipment::get($device_id);
        if (!$device) {
            return json(['code' => 0, 'msg' => '设备不存在']);
        }

        $res = $device->save([
            'holder_type' => model\Equipment::holder_type_center,
            'h_related_id' => $device['center_id'],
            'update_time' => date_now(),
        ]);
        //添加划拨记录
        $res1 = EquipmentLogic::addTransferRecords($device_id, $operator_type, $this->user_id, model\Equipment::holder_type_center, $device['center_id'], '设备回拨');

        if ($res && $res1) {
            return json(['code' => 1, 'msg' => '设备回拨成功']);
        }
        return json(['code' => 0, 'msg' => '设备回拨失败']);
    }

}